package cn.xuyun.cc.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.xuyun.cc.tcp.bean.CommandReq;
import cn.xuyun.cc.tcp.service.MongoService;
import cn.xuyun.cc.tcp.util.Md5Util;
import cn.xuyun.cc.tcp.vo.Constants;

import com.google.gson.stream.JsonReader;

/**
 * Servlet implementation class PutCmdServlet
 */
@WebServlet("/st/PutCmd")
public class PutCmdServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response) <packetreq> <user>xxx</user> --加密账户 <key>xxx</key>
	 *      --请求唯一标识，用于callback <command></command> ----设备命令 <condition
	 *      type=”uid/group/type”>
	 *      ---选择设备id的条件，如果选择uid，下面的item为uid，如果是group，item为groupid
	 *      ，如果是type，item为typeid <item>123</item> <item>45</item> </condition>
	 *      <content></content> -- 参数 <timeout></timeout>
	 *      --超时时间，比如60s，超时时间表示从B接收开始，C执行完成为止所经历的时间 <callback>xxx</callback>
	 *      --callback的请求地址，比如http://domain/pattern.do </packetreq>
	 * 
	 * 
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

//		SAXReader saxReader = new SAXReader();
//
//		try {
//			Document doc = saxReader.read(request.getInputStream());
//			// Element element = doc.getRootElement();
//			Node user = doc.selectSingleNode("/packetreq/user");
//			Node key = doc.selectSingleNode("/packetreq/key");
//			Node cmd = doc.selectSingleNode("/packetreq/command");
//			Attribute cond = (Attribute) doc.selectSingleNode("/packetreq/condition/@type");
//			String type = cond.getValue();
//			List<Node> item = doc.selectNodes("/packetreq/condition/item");
//			Node param = doc.selectSingleNode("/packetreq/content");
//			Node timeout = doc.selectSingleNode("/packetreq/timeout");
//			Node callback = doc.selectSingleNode("/packetreq/callback");
//
//			List<String> deviceId = new ArrayList<String>();
//			if (type.equals("uid")) {
//				for (Node node : item) {
//					deviceId.add(node.getText());
//					// add device unfinished cmdkey
//					MongoService.addCmdKey2Device(key.getText(), node.getText());
//				}
//			}
//
//			// add cmdreq
//			CommandReq cmdreq = new CommandReq();
//			cmdreq.set_id(key.getText());
//			cmdreq.setBegin_time(System.currentTimeMillis());
//			cmdreq.setCallback(callback.getText());
//			cmdreq.setCmdcode(Constants.cmdCode.get(cmd.getText().toUpperCase()));
//			cmdreq.setCmdstr(cmd.getText());
//			cmdreq.setParam(param.getText());
//			cmdreq.setTimeout(Integer.parseInt(timeout.getText().toUpperCase()));
//			cmdreq.setDevice_id(deviceId);
//			cmdreq.setUser(user.getText());
//
//			MongoService.save("command", "command_req", cmdreq);
//
//		} catch (Exception e) {
//
//			e.printStackTrace();
//			response.sendError(405);
//		}
		
		List<String> deviceId = new ArrayList<String>();
		CommandReq cmdreq=null;
		try {
			cmdreq = parseFromJson(request.getInputStream(), deviceId);
			MongoService.save("command", "command_req", cmdreq);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendError(405);
		}
		PrintWriter out=response.getWriter();
		out.print("{\"cmdKey\":\""+cmdreq.get_id()+"\",\"result\":0}");
	}

	public static CommandReq parseFromJson(InputStream is, List<String> deviceId) throws Exception {

		JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
		try {
			CommandReq cmdreq = new CommandReq();
			String key = Md5Util.getMD5(String.valueOf(System.currentTimeMillis()).getBytes());
			cmdreq.set_id(key);
			reader.beginObject();
			while (reader.hasNext()) {
				String name = reader.nextName();
				if (name.equals("user")) {
					String user = reader.nextString();
					cmdreq.setUser(user);
				} else if (name.equals("cmd")) {
					String cmd = reader.nextString();
					cmdreq.setCmdcode(Constants.cmdCode.get(cmd.toUpperCase()));
				} else if (name.equals("callback")) {
					String callback = reader.nextString();
					cmdreq.setCallback(callback);
				} else if (name.equals("timeout")) {
					String timeout = reader.nextString();
					cmdreq.setTimeout(Integer.parseInt(timeout));
				} else if (name.equals("content")) {
					String content = reader.nextString();
					cmdreq.setCmdstr(content);
				} else if (name.equals("device")) {
					reader.beginArray();
					while (reader.hasNext()) {
						String uid = reader.nextString();
						deviceId.add(uid);
						MongoService.addCmdKey2Device(key, uid);
					}
					reader.endArray();

				} else if (name.equals("")) {

				} else {
					reader.skipValue();
				}
			}
			reader.endObject();
			cmdreq.setDevice_id(deviceId);
			return cmdreq;
		} finally {
			reader.close();
		}

	}

}
